package com.meida.module.bus.provider.service.impl;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.client.entity.BusAfterservice;
import com.meida.module.bus.client.entity.BusOrder;
import com.meida.module.bus.client.entity.BusOrderAnswer;
import com.meida.module.bus.client.enums.OrderAfterServiceEnum;
import com.meida.module.bus.client.enums.OrderTypeEnum;
import com.meida.module.bus.provider.mapper.BusAfterserviceMapper;
import com.meida.module.bus.provider.service.BusAfterserviceService;
import com.meida.module.bus.provider.service.BusOrderAnswerService;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.pay.provider.service.PayBalanceService;
import com.meida.msg.client.entity.MsgReceive;
import com.meida.msg.provider.service.MsgReceiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 订单售后接口实现类
 *
 * @author flyme
 * @date 2021-08-03
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusAfterserviceServiceImpl extends BaseServiceImpl<BusAfterserviceMapper, BusAfterservice> implements BusAfterserviceService {

    @Autowired
    private BusOrderService busOrderService;

    @Autowired
    private BusOrderAnswerService busOrderAnswerService;

    @Autowired
    private MsgReceiveService msgReceiveService;

    @Autowired
    private PayBalanceService payBalanceService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusAfterservice afterservice, EntityMap extra) {
        return ResultBody.ok();
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusAfterservice> cq, BusAfterservice afterservice, EntityMap requestMap) {
        cq.orderByDesc("afterservice.createTime");
        return ResultBody.ok();
    }

    @Override
    public Integer totalAfterServiceOrderNum(Long answerUserId) {
        CriteriaQuery cq = new CriteriaQuery(BusAfterservice.class);
        cq.createJoin(BusOrder.class).setMainField("orderId").setJoinField("orderId");
        cq.eq(BusOrder.class, "answerUserId", answerUserId);
        return baseMapper.totalAfterServiceOrderNum(cq);
    }

    @Override
    public ResultBody checkOrderAfterService(Long afterServiceId, Integer state, String auditMind) {
        BusAfterservice afterservice = getById(afterServiceId);
        if (FlymeUtils.isEmpty(afterservice)) {
            return ResultBody.failed("售后信息不存在");
        }
        afterservice.setState(state);
        afterservice.setAuditMind(auditMind);
        boolean result = updateById(afterservice);
        if (result) {
            //todo 售后审核通过之后,需要退款(学霸账户已发放佣金退回,用户留币余额需退回,订单状态需修改)
            if (OrderAfterServiceEnum.checkPass.getValue().equals(state)) {
                Long orderId = afterservice.getOrderId();
                BusOrder busOrder = busOrderService.getById(orderId);
                if (FlymeUtils.isNotEmpty(busOrder)) {
                    //todo 学霸佣金扣除
                    Long answerUserId = busOrder.getAnswerUserId();
                    BigDecimal commissionAmount = busOrder.getCommission();
                    //todo 用户留币退回(退回订单金额,赏金,使用优惠券)
                    Long userId = busOrder.getUserId();
                    //更新订单状态为已退款
                    busOrderService.updateOrderState(orderId, "7");
                }
            }
            //如果审核失败订单状态还为售后处理中?
            return ResultBody.ok();
        }
        return ResultBody.failed("审核失败");
    }

    @Override
    public BigDecimal sumAmountByState(Integer state) {
        CriteriaQuery cq = new CriteriaQuery(BusAfterservice.class);
        cq.addSelect("COALESCE(sum(payableAmount),0) amount");
        cq.eq("state", state);
        cq.createJoin(BusOrder.class).setMainField("orderId").setJoinField("orderId");
        EntityMap one = findOne(cq);
        BigDecimal amount = one.getBigDecimal("amount");
        return amount;
    }

    @Override
    public BusAfterservice getByOrderId(Long orderId) {
        CriteriaQuery cq = new CriteriaQuery(BusAfterservice.class);
        cq.eq(true, "orderId", orderId);
        return getOne(cq);
    }

    @Override
    public void applyBusAfterservice(Long orderId) {
        BusOrderAnswer orderAnswer = busOrderAnswerService.getAnswerByOrderId(orderId);
        Long userId = OpenHelper.getUserId();
        BusAfterservice busAfterservice = new BusAfterservice();
        busAfterservice.setUserId(userId);
        busAfterservice.setState(0);
        //申请退款会出现答案不存在的情况（预约辅导超时未接单）
        if (FlymeUtils.isNotEmpty(orderAnswer)) {
            Long answerId = orderAnswer.getAnswerId();
            busAfterservice.setAnswerId(answerId);
        }
        busAfterservice.setOrderId(orderId);
        busAfterservice.setAfterDescribe("超时自动申请退款");
        boolean save = save(busAfterservice);
        if (save) {
            //更新订单为售后处理中，3个类型订单状态一致
            BusOrder busOrder = busOrderService.getById(orderId);
            Integer orderType = busOrder.getOrderType();
            Long orderUserId = busOrder.getUserId();
            busOrderService.updateOrderState(orderId, "6");
            OrderTypeEnum orderTypeEnum = OrderTypeEnum.getByValue(orderType);
            String orderTypeDesc = orderTypeEnum.getLabel();
            String msgTitle = orderTypeDesc + "，申请售后通知";
            String msgContent = "您申请的" + orderTypeDesc + "售后，平台已收到，客服人员进行审核中！感谢您使用留同学APP";
            MsgReceive msgReceive = msgReceiveService.sendMsgReceiveNotice(BusOrder.class.getSimpleName(), orderUserId, msgTitle, msgContent);
            busOrderService.orderPushMessage(msgReceive, msgTitle, msgContent);
        }

    }
}
